package com.dctp.ems.controller;

import com.dctp.common.controller.BaseController;
import com.dctp.common.cache.FxRateCache;
import com.dctp.common.utils.DateUtil;
import com.dctp.common.utils.NumberUtil;
import com.dctp.common.vo.JsonResult;
import com.dctp.common.vo.PageResult;
import com.jfinal.aop.Before;
import com.jfinal.core.Path;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Path("/fxRate")
public class FxRateController extends BaseController {

    /**
     * GET /fxRate/list
     * 分页查询汇率
     */
    public void list() {
        int page = getInt("currentPage", 1);
        int pageSize = getInt("pageSize", 10);
        String code = getPara("code", "");
        String targetCode = getPara("target_code", "");
        String status = getPara("status", "");
        StringBuilder where = new StringBuilder(" WHERE 1=1 ");
        List<Object> params = new ArrayList<>();
        if (!code.isEmpty()) {
            where.append(" AND code LIKE ?");
            params.add('%' + code + '%');
        }
        if (!targetCode.isEmpty()) {
            where.append(" AND target_code LIKE ?");
            params.add('%' + targetCode + '%');
        }
        if (!status.isEmpty()) {
            where.append(" AND status = ?");
            params.add(status);
        }
        String select = "SELECT * ";
        String from = "FROM dctp_fx_rate" + where + " ORDER BY id DESC";
        var p = Db.paginate(page, pageSize, select, from, params.toArray());
        renderJson(JsonResult.successWithData(
            new PageResult<>(p.getList(), p.getTotalRow(), pageSize, page)
        ));
    }

    /**
     * POST /fxRate/add
     * 添加汇率
     */
    @Before(Tx.class)
    public void add() {
        Record body = jsonBody();
        if (body.get("code") == null || body.get("target_code") == null) {
            renderJson(JsonResult.failWithMessage("code和target_code不能为空"));
            return;
        }
        if (!isValidRate(body.get("rate"))) {
            renderJson(JsonResult.failWithMessage("汇率必须为正数"));
            return;
        }
        // 检查唯一
        Long exist = Db.queryLong("SELECT id FROM dctp_fx_rate WHERE code=? AND target_code=?", body.getStr("code"), body.getStr("target_code"));
        if (exist != null) {
            renderJson(JsonResult.failWithMessage("该币种对已存在"));
            return;
        }
        body.set("create_time", DateUtil.now());
        if (!Db.save("dctp_fx_rate", body)) {
            throw new RuntimeException("新增汇率失败");
        }
        renderJson(JsonResult.success());
    }

    /**
     * POST /fxRate/update/:id
     * 更新汇率
     */
    @Before(Tx.class)
    public void update() {
        Integer id = getParaToInt(0);
        if (id == null) {
            renderJson(JsonResult.failWithMessage("参数缺失"));
            return;
        }
        Record body = jsonBody();
        if (body.getColumns().isEmpty()) {
            renderJson(JsonResult.failWithMessage("无有效字段"));
            return;
        }
        if (body.get("rate") != null && !isValidRate(body.get("rate"))) {
            renderJson(JsonResult.failWithMessage("汇率必须为正数"));
            return;
        }
        body.set("id", id)
            .set("update_time", DateUtil.now());
        boolean updated = Db.update("dctp_fx_rate", body);
        if (!updated) {
            renderJson(JsonResult.failWithMessage("更新失败或记录不存在"));
            return;
        }
        // 清理缓存
        String code = body.getStr("code");
        String targetCode = body.getStr("target_code");
        if (code == null || targetCode == null) {
            Record dbRec = Db.findById("dctp_fx_rate", id);
            if (dbRec != null) {
                code = dbRec.getStr("code");
                targetCode = dbRec.getStr("target_code");
            }
        }
        // 清理缓存
        try {
            if (code != null && targetCode != null) {
                FxRateCache.delete(code, targetCode);
            }
        }catch (Exception e){}
        renderJson(JsonResult.success());
    }

    /**
     * POST /fxRate/delete/:id
     * 删除汇率
     */
    @Before(Tx.class)
    public void delete() {
        Integer id = getParaToInt(0);
        if (id == null) {
            renderJson(JsonResult.failWithMessage("参数缺失"));
            return;
        }
        Record dbRec = Db.findById("dctp_fx_rate", id);
        int r = Db.update("DELETE FROM dctp_fx_rate WHERE id=?", id);
        if( r == 0) {
            renderJson(JsonResult.failWithMessage("删除失败或记录不存在"));
        } else {
            // 清理缓存
            try {
                if (dbRec != null) {
                    String code = dbRec.getStr("code");
                    String targetCode = dbRec.getStr("target_code");
                    if (code != null && targetCode != null) {
                        FxRateCache.delete(code, targetCode);
                    }
                }
            }catch (Exception e){}
            renderJson(JsonResult.success());
        }
    }

    /**
     * GET /fxRate/all
     * 获取所有启用状态的汇率
     */
    public void all() {
        List<Record> list = Db.find("SELECT * FROM dctp_fx_rate WHERE status = 1 ORDER BY id DESC");
        renderJson(JsonResult.successWithData(list));
    }

    private boolean isValidRate(Object rate) {
        if (!NumberUtil.isValidDecimal(rate)) return false;
        try {
            return new BigDecimal(rate.toString()).compareTo(BigDecimal.ZERO) > 0;
        } catch (Exception e) {
            return false;
        }
    }
}
